package com.cn.stepLock.chain;

import com.cn.stepLock.chain.ChainHelper;
import com.cn.stepLock.event.BaseEvent;
import com.cn.stepLock.exception.MessageException;
import com.cn.stepLock.lambda.LambdaUtil;
import com.cn.stepLock.listener.*;
import com.google.common.collect.ImmutableList;

import java.util.EventListener;
import java.util.List;

import static com.cn.stepLock.lambda.LambdaUtil.findOne;

/**
 * @author Aaron
 * @desc
 * @createTime 2022-02-24 6:16
 * @since
 */
public class ChainEventApplication {
    private static List<BaseListener> eventListenerList;

    public static void pulishEvent(BaseEvent baseEvent){
        baseEvent.getEventListenerList().forEach(x->x.handleEvent(baseEvent));
    }

    public static void initListenerList(ChainHelper chainHelper){
        eventListenerList= ImmutableList.of(new StartExecuteTaskListener(chainHelper),
                new StartProcessTaskListener(chainHelper),
                new FinishTaskListener(chainHelper),
                new OfferTaskToSynchronizedChainListener(chainHelper),
                new OfferTaskToParkChainListener(chainHelper));
    }

    public static String getListenerName(Class clazz){
        return clazz.getSimpleName();
    }

    public static BaseListener getEventListener(Class clazz){
        return findOne(eventListenerList,x->getListenerName(clazz).equalsIgnoreCase(x.getName())).orElseThrow(()->new MessageException("can not find this listener!"));
    }
}
